from flask import session,request, jsonify
from info.utils.response_code import RET
from info.models import User, News, Category
from . import index_blue
from info import redis_store
import logging
from flask import current_app,render_template

@index_blue.route('/newslist')
def newslist():
    # - 1, 获取参数
    #cid是什么？???????
    cid = request.args.get("cid","1")
    page = request.args.get("page","1")
    per_page = request.args.get("per_page","5")
    # - 2, 参数类型转换(整数), 方便做分页查询
    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        page = 1 # 返回数字是什么意思
        per_page=5 # 返回数字是什么意思
    # - 3, 分页查询数据, 组织数据
    try:
        condition = ""
        if cid != "1":
            condition = (News.category_id == cid)
        paginate = News.query.filter(condition).order_by(News.create_time.desc()).paginate(page,per_page,False)
    except Exception as e:
        current_app.logger.error(e)
        #errno=RET.DBERR这意思不懂
        return jsonify(errno=RET.DBERR,errmsg="获取新闻失败")

    totalPage = paginate.pages
    items = paginate.items#当前页的所有对象
    currentPage = paginate.page
    # 3.1将对象列表转成字典列表
    newlist = []
    for news in items:
        newlist.append(news.to_dict())
    # - 4, 返回响应, 携带数据
    return jsonify(errno=RET.OK,errmsg="获取成功",totalPage=totalPage,currentPage=currentPage,newsList=newlist)

@index_blue.route('/',methods=["GET","POST"])
def show_index():
    #1,获取session用户编号
    user_id = session.get("user_id")
    #2,根据用户编号获取对象
    user = None
    if user_id:
        user = User.query.get(user_id)

    #3按照点击量查询前10条新闻
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(10).all()
    except Exception as e:
        current_app.logger.error(e)
    #4,将新闻的对象列表转换成新闻的字典列表
    click_news_list = []
    for news in news_list:
        click_news_list.append(news.to_dict())

    #查询所有的分类  转成字典列表
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
    Category_list = []
    for category in categories:
        Category_list.append(category.to_dict())

    #携带数据渲染页面
    dict_data = {
        "user_info":user.to_dict() if user else "",
        'click_news_list': click_news_list,
        "categories":Category_list
    }
    return render_template("news/index.html",dict_data=dict_data)



#处理网站logo
@index_blue.route('/favicon.ico')
def get_logo():
    response =  current_app.send_static_file("news/favicon.ico")
    return response